//
//  ReleaseSocialViewController.m
//  ShowYork
//
//  Created by hxh on 2020/9/21.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "MineCreateOpusViewController.h"
#import "HomePageDetailViewController.h"
#import "SLEditVideoController.h"

#import "ZLPhotoBrowser-Swift.h"
#import "LFAssetExportSession.h"
#import "MineCreateOpusHeaderView.h"

#import "MineCreateOpusPostCell.h"
#import "SocialVideoItemCell.h"
#import "MineCreateOpusTypeHeaderView.h"

#import "HomePageItemModel.h"
#import "SocialReleaseModel.h"
#import "SocialMainTagModel.h"
#import "SocialSubTagModel.h"
#import "SocialSeqModel.h"


#define videoHeight 220
#define videoWidth (videoHeight/4*3)

#define photoWidth (kScreenW - 50 - 16 - 8)/3


@interface MineCreateOpusViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,MineCreateOpusHeaderViewDelegate,MineCreateOpusPostCellDelegate,SocialVideoItemCellDelegate,MineCreateOpusTypeHeaderViewDelegate,LFAssetExportSessionDelegate>

@property (nonatomic,strong)UICollectionView *collectionView;
/// 正在拖拽的indexpath
@property (nonatomic,strong)NSIndexPath *dragingIndexPath;
/// 目标位置
@property (nonatomic,strong)NSIndexPath *targetIndexPath;

@property (nonatomic,strong)UIImageView *dragingImgView;

@property (nonatomic,strong)UIView *deleteView;

@property (nonatomic,strong)UIButton *confirmBtn;

@property (nonatomic,strong)UIButton *cancelBtn;

@property (nonatomic,copy)NSString *content;

@property (nonatomic,strong)NSMutableArray *urls;

@property (nonatomic,strong)NSMutableArray *postItems;


@property (nonatomic,strong)NSMutableArray *dataArray;

@property (nonatomic,strong)SocialSubTagModel *currentTagItem;

@end

@implementation MineCreateOpusViewController



- (NSMutableArray *)postItems{
    if (!_postItems) {
        _postItems = [NSMutableArray array];
    }
    return _postItems;
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)urls{
    if (!_urls) {
        _urls = [NSMutableArray array];
    }
    return _urls;
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
   
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
   
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
}

- (instancetype)initWithPostItem:(SocialReleaseModel *)itemModel{
    if (self = [super init]) {
        [self.postItems addObject:itemModel];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setUI];
    [self registNote];
    
    [self loadTopicList];
}

- (void)setUI{

    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH - kNavBarHeight) collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.alwaysBounceVertical = YES;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    
    [self.collectionView registerClass:[MineCreateOpusHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MineCreateOpusHeaderView"];
    [self.collectionView registerClass:[MineCreateOpusPostCell class] forCellWithReuseIdentifier:@"MineCreateOpusPostCell"];
    [self.collectionView registerClass:[SocialVideoItemCell class] forCellWithReuseIdentifier:@"SocialVideoItemCell"];
    [self.collectionView registerClass:[MineCreateOpusTypeHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"MineCreateOpusTypeHeaderView"];
    [self.view addSubview:self.collectionView];
        
    self.dragingImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0,kNavBarHeight,photoWidth,photoWidth)];
    self.dragingImgView.hidden = YES;
    self.dragingImgView.layer.masksToBounds = YES;
    self.dragingImgView.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:self.dragingImgView];
    
    [[UIApplication sharedApplication].keyWindow addSubview:self.deleteView];
    
    self.cancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
    [self.cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [self.cancelBtn setTitleColor:C102 forState:UIControlStateNormal];
    self.cancelBtn.titleLabel.font = font(17);
    [self.cancelBtn addTarget:self action:@selector(cancelMethod) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.cancelBtn];
    
    self.confirmBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 70, 28)];
    [self.confirmBtn setTitle:@"发布" forState:UIControlStateNormal];
    [self.confirmBtn setTitleColor:RGBA(255, 255, 255, 1) forState:UIControlStateNormal];
    [self.confirmBtn setTitleColor:RGBA(255, 255, 255, 1) forState:UIControlStateSelected];
    [self.confirmBtn setTitleColor:RGBA(255, 255, 255, 1) forState:UIControlStateHighlighted];
    self.confirmBtn.titleLabel.font = font(15);
    self.confirmBtn.backgroundColor = RGBA(224, 224, 224, 1);
    self.confirmBtn.layer.cornerRadius = 14;
    self.confirmBtn.layer.masksToBounds = YES;
    self.confirmBtn.userInteractionEnabled = NO;
//    [self.confirmBtn setBackgroundImage:[UIImage imageNamed:@"social_confirm_tag"] forState:UIControlStateNormal];
    [self.confirmBtn setBackgroundImage:[UIImage imageNamed:@"social_confirm_tag"] forState:UIControlStateHighlighted];
    [self.confirmBtn setBackgroundImage:[UIImage imageNamed:@"social_confirm_tag"] forState:UIControlStateSelected];
    [self.confirmBtn addTarget:self action:@selector(confirmMethod) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.confirmBtn];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.collectionView.backgroundColor = [UIColor whiteColor];

   
}

#pragma mark - 接口相关
- (void)loadTopicList{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:PostTagList];
    param[@"pageIndex"] = @1;
    param[@"pageSize"] = @9999;
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(PostTagList) parames:param success:^(id responseObj) {
        NSArray *dataArray = [SocialMainTagModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];
        NSMutableArray *ids = [NSMutableArray array];
        [dataArray enumerateObjectsUsingBlock:^(SocialMainTagModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [obj.tagSubsetList enumerateObjectsUsingBlock:^(SocialSubTagModel * _Nonnull subOject, NSUInteger subIndex, BOOL * _Nonnull stop) {
                // 去重
                if (![ids containsObject:subOject.id]) {
                    [ids addObject:subOject.id];
                    [self.dataArray addObject:subOject];
                }
               
            }];
        }];
        [self.collectionView reloadData];
    } failure:^(id error) {
       
    }];
}

#pragma mark - 长按手势
-(void)longPressMethod:(UILongPressGestureRecognizer*)gestureRecongnizer{
    
    CGPoint point = [gestureRecongnizer locationInView:self.collectionView];
    switch (gestureRecongnizer.state) {
        case UIGestureRecognizerStateBegan:
            [self dragBegin:point];
            break;
        case UIGestureRecognizerStateChanged:
            [self dragChange:point];
            break;
        case UIGestureRecognizerStateEnded:
            [self dragEnd:point];
            break;
        default:
            break;
    }
}

#pragma mark - 导航栏按钮点击事件
- (void)cancelMethod{

    if (self.postItems.count != 0 || (![self.content isSpaceString] && self.content.length > 0)) {
        
        NSString *att = @"未发布的内容退出将不做保存";
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"确定退出？" message:att preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alertController dismissViewControllerAnimated:YES completion:nil];

        }];
        
        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.view endEditing:YES];
            [alertController dismissViewControllerAnimated:YES completion:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }];
        NSMutableAttributedString *alertControllerMessageStr = [[NSMutableAttributedString alloc] initWithString:att];
        [alertControllerMessageStr addAttribute:NSForegroundColorAttributeName value:C102 range:NSMakeRange(0, att.length)];
        [alertControllerMessageStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, att.length)];
        [alertController setValue:alertControllerMessageStr forKey:@"attributedMessage"];
        
        [cancelAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
        [confirmAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
        //往alertViewController上添加alertAction
        [alertController addAction:confirmAction];
        [alertController addAction:cancelAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        [self.view endEditing:YES];
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)confirmMethod{
    
    [self.view endEditing:YES];
    
    [SVProgressHUD showWithStatus:@"作品正在发布中..."];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = paths.firstObject;
    NSString *myPathDocs = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"mergeSlowMoVideo-%d.MP4",arc4random() % 1000]];
    NSURL *outPath = [NSURL fileURLWithPath:myPathDocs];
    SocialReleaseModel *itemModel = self.postItems.firstObject;
    AVURLAsset *asset = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:itemModel.videoUrl]];
    LFAssetExportSession *encoder = [LFAssetExportSession exportSessionWithAsset:asset preset:LFAssetExportSessionPreset720P];
    encoder.delegate = self;
    encoder.outputFileType = AVFileTypeMPEG4;
    encoder.outputURL = outPath; // 视频输出路径
    __weak typeof(self)weakSelf = self;
    [encoder exportAsynchronouslyWithCompletionHandler:^
       {
           if (encoder.status == AVAssetExportSessionStatusCompleted)
           {
               NSLog(@"video size:%.2fMB", [encoder.outputURL.relativePath lf_fileSize]/1024.0/1024.0);
                
               NSData *data = [NSData dataWithContentsOfFile:encoder.outputURL.path];
               RNNetworkParam *param = [[RNNetworkParam alloc]init];
               param.data = data;
               param.mimeType = @"video/mp4";
               param.name = @"file";
               NSDate *date = [NSDate date];
               NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
               formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
               param.filename =  [NSString stringWithFormat:@"%@.mp4",[formatter stringFromDate:date]];
               [[RPNetworkExtensionTool sharedTool] uploadWithURLString:kGET_REQUEST_URL(DdupUpload) parameters:nil uploadParam:@[param] success:^(id responseObj) {
                   NSString *url = responseObj[RESPONSE];
                   [weakSelf.urls addObject:url];
                   dispatch_async(dispatch_get_main_queue(), ^{
                       [weakSelf userPost];
                   });

               } failure:^(NSError *error) {

               }];
           }else if (encoder.status == AVAssetExportSessionStatusCancelled){
               [weakSelf updateLoadVideoWithItemModel:itemModel];
           }else{
               [weakSelf updateLoadVideoWithItemModel:itemModel];
           }
       }];
}



- (void)updateLoadVideoWithItemModel:(SocialReleaseModel *)itemModel{
   
    NSData *data = [NSData dataWithContentsOfFile:itemModel.videoUrl];
    RNNetworkParam *param = [[RNNetworkParam alloc]init];
    param.data = data;
    param.mimeType = @"video/mp4";
    param.name = @"file";
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    param.filename =  [NSString stringWithFormat:@"%@.mp4",[formatter stringFromDate:date]];
    [[RPNetworkExtensionTool sharedTool] uploadWithURLString:kGET_REQUEST_URL(DdupUpload) parameters:nil uploadParam:@[param] success:^(id responseObj) {
        NSString *url = responseObj[RESPONSE];
        [self.urls addObject:url];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self userPost];
        });

    } failure:^(NSError *error) {

    }];
}


#pragma mark - 发布动态
- (void)userPost{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    if (self.urls.count != 0) {
        NSMutableArray *seqUrl = [NSMutableArray array];
        [self.urls enumerateObjectsUsingBlock:^(NSObject * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isKindOfClass:[NSString class]]) {
                SocialSeqModel *model = [[SocialSeqModel alloc]init];
                model.postUrl = (NSString *)obj;
                model.seq = @(idx);
                [seqUrl addObject:[model mj_JSONObject]];
            }
        }];
        param[@"seqUrl"] = seqUrl;
        param[@"contentType"] = @3;
    }
    if (self.content.length != 0) {
        param[@"contentText"] = self.content;
    }
    param[@"type"] = @"2";
    param[@"tagId"] = self.currentTagItem.id;
    param[@"tagStr"] = self.currentTagItem.tagName;
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"contentText"] = self.content;
    param[@"md5"] = [RPAppManager md5StrWithApi:UserPost];
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(UserPost) parames:param success:^(id responseObj) {
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_success"] message:@"发布成功" originY:0 duration:2 finishHandler:nil];
        [MobClick event:@"issus_post_success"];
        
        [self.navigationController popViewControllerAnimated:NO];
    
        // 刷新我的和动态列表页面数据
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateUserInfoOpusList" object:nil];
        
    } failure:^(NSError *error) {
        
        [self.urls removeAllObjects];
        
        [WHToast showErrorWithMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}

#pragma mark -拖拽开始
-(void)dragBegin:(CGPoint)point{
    
    [self.view endEditing:YES];
    
    if (self.postItems.count == 0) {
        return;
    }
    
    self.dragingImgView.size = CGSizeMake(photoWidth, photoWidth);
    
    if (self.postItems.count != 0) {
        self.dragingImgView.size = CGSizeMake(videoWidth,videoHeight);
    }
    
    self.dragingIndexPath = [self getDragingIndexPathWithPoint:point];
    if (!_dragingIndexPath) {return;}
    [self showDeleteViewAnimation];
    SocialVideoItemCell *dragingCell = (SocialVideoItemCell *)[self.collectionView cellForItemAtIndexPath:self.dragingIndexPath];
    dragingCell.hidden = YES;
    //更新被拖拽的item
    self.dragingImgView.hidden = NO;
    self.dragingImgView.center = CGPointMake(point.x, point.y- self.collectionView.contentOffset.y);
    SocialReleaseModel *model = self.postItems[self.dragingIndexPath.row];
    self.dragingImgView.image = model.image;
    [self.dragingImgView setTransform:CGAffineTransformMakeScale(1.1, 1.1)];
}

#pragma mark -正在被拖拽
-(void)dragChange:(CGPoint)point{
    if (!_dragingIndexPath) {return;}
    self.dragingImgView.center = CGPointMake(point.x, point.y- self.collectionView.contentOffset.y);;
    self.targetIndexPath = [self getTargetIndexPathWithPoint:point];
    if (self.dragingIndexPath) {
        if (CGRectGetMaxY(self.dragingImgView.frame) > kScreenH  - 100) {
            [self setDeleteViewDeleteState];
        }else{
            [self setDeleteViewNormalState];
        }
    }
    //与目标cell交换位置
    if (_dragingIndexPath && _targetIndexPath) {
        if (_dragingIndexPath.section == _targetIndexPath.section) {
            [self.collectionView performBatchUpdates:^{
                [self.collectionView moveItemAtIndexPath:_dragingIndexPath toIndexPath:_targetIndexPath];
                _dragingIndexPath = _targetIndexPath;
            } completion:^(BOOL finished) {
                if (self.dragingImgView.hidden && finished) {
                    [self.collectionView reloadData];
                }
            }];
        }
    }
}

#pragma mark -拖拽结束
-(void)dragEnd:(CGPoint)point{
    
    [self hiddenDeleteViewAnimation];
    if (!self.dragingIndexPath) {return;}
    if (CGRectGetMaxY(self.dragingImgView.frame) > kScreenH  - 100) {
        self.dragingImgView.hidden = YES;
        [self setDeleteViewNormalState];
        [self.postItems removeObjectAtIndex:self.dragingIndexPath.item];
        SocialVideoItemCell *item = (SocialVideoItemCell*)[self.collectionView cellForItemAtIndexPath:self.dragingIndexPath];
        item.hidden = NO;
        [self.collectionView reloadData];

    }else{
        CGRect endFrame = [self.collectionView cellForItemAtIndexPath:self.dragingIndexPath].frame;
        endFrame.origin.y -= self.collectionView.contentOffset.y;//UIScrollView 及其子类都会相对父View发生偏移
        [self.dragingImgView setTransform:CGAffineTransformMakeScale(1.0, 1.0)];
        SocialVideoItemCell *item = (SocialVideoItemCell*)[self.collectionView cellForItemAtIndexPath:self.dragingIndexPath];
        [UIView animateWithDuration:0.3 animations:^{
            self.dragingImgView.frame = endFrame;
        }completion:^(BOOL finished) {
            self.dragingImgView.hidden = YES;
            item.hidden = NO;
        }];
    }
    [self changeConfirmBtnStatus];
}
#pragma mark -获取被拖动的Cell的IndexPath
-(NSIndexPath*)getDragingIndexPathWithPoint:(CGPoint)startPoint{
    NSIndexPath* dragIndexPath = nil;
    for (NSIndexPath *indexPath in self.collectionView.indexPathsForVisibleItems) {
        //获取当前点所在的cell  且cell不能是添加图片按钮
        if (CGRectContainsPoint([self.collectionView cellForItemAtIndexPath:indexPath].frame, startPoint)) {
            if (indexPath.row == self.postItems.count) {
                return nil;
            }else{
                dragIndexPath = indexPath;
                return dragIndexPath;
            }
        }
    }
    return dragIndexPath;
}

#pragma mark -获取目标Cell的IndexPath
-(NSIndexPath*)getTargetIndexPathWithPoint:(CGPoint)movePoint{
    NSIndexPath *targetIndexPath = nil;
    for (NSIndexPath *indexPath in self.collectionView.indexPathsForVisibleItems) {
        //获取目标点所在的cell  且cell不能是添加图片按钮 如果是起点cell 也没必要交换
        if ([indexPath isEqual:self.dragingIndexPath]) {continue ;}
        if (CGRectContainsPoint([self.collectionView cellForItemAtIndexPath:indexPath].frame, movePoint) && indexPath.row != self.postItems.count) {
            targetIndexPath = indexPath;
        }
    }
    return targetIndexPath;
}


#pragma mark - 处理通知
- (void)registNote{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateVideoItem:) name:@"updateReleaseVideo" object:nil];
}

- (void)updateVideoItem:(NSNotification *)note{
    NSString *videoPath = note.userInfo[@"data"];
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:videoPath] options:nil];
    AVAssetImageGenerator *assetGen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetGen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [assetGen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *videoImage = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    
    SocialReleaseModel *itemModel = [[SocialReleaseModel alloc]init];
    itemModel.isVideo = YES;
    itemModel.videoUrl = videoPath;
    itemModel.image = videoImage;
    [self.postItems removeAllObjects];
    [self.postItems addObject:itemModel];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self changeConfirmBtnStatus];
        [self.collectionView reloadData];
    });
}

- (void)popToRootViewControllerByRemoteMessage{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)setAuthStatusWithMessage:(NSString *)message{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [alertController dismissViewControllerAnimated:YES completion:nil];
        // 去设置相册权限
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication]canOpenURL:url]) {
            [[UIApplication sharedApplication]openURL:url options:@{} completionHandler:nil];
        }
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [alertController dismissViewControllerAnimated:YES completion:nil];
    }];
    [confirmAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
    [cancelAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
    //往alertViewController上添加alertAction
    [alertController addAction:cancelAction];
    [alertController addAction:confirmAction];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

#pragma mark - 底部删除 视图
- (UIView *)deleteView{
    if (!_deleteView) {
        _deleteView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenH, kScreenW, 100)];
        _deleteView.backgroundColor = RGBA(213, 43, 41, 0.8);
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = 201809;
        [button setImage:[UIImage imageNamed:@"social_tag_select"] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"social_tag_selected"] forState:UIControlStateSelected];
        [button setTitle:@"拖动到此处删除" forState:UIControlStateNormal];
        [button setTitle:@"松手即可删除" forState:UIControlStateSelected];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        [button layoutButtonWithEdgeInsetsStyle:TYButtonEdgeInsetsStyleTop imageTitleSpace:30];
        [_deleteView addSubview:button];
        [button sizeToFit];
        CGRect frame = button.frame;
        frame.origin.x = (_deleteView.frame.size.width - frame.size.width) / 2;
        frame.origin.y = (100 - frame.size.height) / 2 + 5;
        button.frame = frame;
        
        [[UIApplication sharedApplication].keyWindow addSubview:_deleteView];
    }
    return _deleteView;
}

- (void)showDeleteViewAnimation{
    self.deleteView.hidden = NO;
    [UIView animateWithDuration:0.25 animations:^{
        self.deleteView.transform = CGAffineTransformTranslate(self.deleteView.transform, 0, -100);

    } completion:^(BOOL finished) {

    }];
}

- (void)hiddenDeleteViewAnimation{
    [UIView animateWithDuration:0.25 animations:^{
        self.deleteView.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        
    }];
}

- (void)setDeleteViewDeleteState{
    UIButton *button = (UIButton *)[_deleteView viewWithTag:201809];
    button.selected = YES;
}

- (void)setDeleteViewNormalState{
    UIButton *button = (UIButton *)[_deleteView viewWithTag:201809];
    button.selected = NO;
}
#pragma mark - collectionViewDelegate

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 1;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.postItems.count != 0) {
        SocialVideoItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SocialVideoItemCell" forIndexPath:indexPath];
        SocialReleaseModel *model = self.postItems.firstObject;
        [cell setVideoImg:model.image];
        cell.delegate = self;
        // 添加手势
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressMethod:)];
        [cell addGestureRecognizer:longPress];
        
        return cell;
    }
    MineCreateOpusPostCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MineCreateOpusPostCell" forIndexPath:indexPath];
    cell.delegate = self;
    return cell;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionHeader) {
        MineCreateOpusHeaderView * header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"MineCreateOpusHeaderView" forIndexPath:indexPath];
        [header setContent:self.content];
        header.delegate = self;
        return header;
    }
    if (kind == UICollectionElementKindSectionFooter) {
        MineCreateOpusTypeHeaderView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier: @"MineCreateOpusTypeHeaderView" forIndexPath:indexPath];
        [header setDataArray:self.dataArray];
        header.delegate = self;
        return header;
    }
    return nil;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

}

#pragma mark - layoutDelegate
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.postItems.count == 0) {
        return CGSizeMake(photoWidth, photoWidth);
    }
    return CGSizeMake(videoWidth,videoHeight);
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
        return UIEdgeInsetsMake(32, 16, 32, 0);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0.0f;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0.0f;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(kScreenW,IPHONE_X?230:180);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    return CGSizeMake(kScreenW, [self getTypeListHeight]);
}

#pragma mark - SocialVideoItemCellDelegate

- (void)showVideo{
    __weak typeof(self)weakSelf = self;
    SocialReleaseModel *model = self.postItems.firstObject;
    [MGJRouter openURL:@"local://ddup/releaseVideoBrowser" withUserInfo:@{@"navigationVC":self.navigationController,@"url":model.videoUrl,@"block":^(void){
        [weakSelf.postItems removeAllObjects];
        [weakSelf.collectionView reloadData];
        [weakSelf changeConfirmBtnStatus];
    },} completion:nil];
}

- (void)addVideo{

    if (![RPAppManager checkVideoPhotoAuthorization]) {
        [self setAuthStatusWithMessage:@"此功能需要您授权本App打开照片\n设置方法: 打开手机设置->隐私->照片"];
        return;
    }
  
    [ZLPhotoConfiguration default].maxSelectCount = 1;
    [ZLPhotoConfiguration default].allowSelectVideo = true;
    [ZLPhotoConfiguration default].showSelectBtnWhenSingleSelect = false;
    [ZLPhotoConfiguration default].maxSelectVideoDuration = 3600;
    [ZLPhotoConfiguration default].allowSelectImage = false;
    [ZLPhotoConfiguration default].allowMixSelect = false;
    [ZLPhotoConfiguration default].allowEditImage = false;
    [ZLPhotoConfiguration default].allowSelectOriginal = false;
    [ZLPhotoConfiguration default].allowTakePhoto = false;
    [ZLPhotoConfiguration default].allowRecordVideo = false;
    [ZLPhotoConfiguration default].enablePhotoClip = false;
    [ZLPhotoConfiguration default].allowPreviewVideo = true;
    [ZLPhotoConfiguration default].themeColorDeploy.navEmbedTitleViewBgColor = [UIColor clearColor];
    [ZLPhotoConfiguration default].customImageNames = @[@"zl_retake",@"zl_albumSelect",@"zl_downArrow",@"zl_btn_selected",@"zl_btn_unselected",@"zl_video"];
    [ZLPhotoConfiguration default].bottomToolViewBtnBgImageShow = YES;
    [ZLPhotoConfiguration default].botomToolViewBtnBgImageName = @"social_confirm_tag";
    [ZLPhotoConfiguration default].themeColorDeploy.bottomToolViewBtnNormalBgColor = RGBA(245, 75, 100, 1);
    [ZLPhotoConfiguration default].navTitleFont = [UIFont boldSystemFontOfSize:16];
    [ZLPhotoConfiguration default].customLanguageKeyValue_objc = @{@"ok":@"我知道了",@"done":@"完成"};
    [ZLPhotoConfiguration default].showInvalidMask = true;
    [ZLPhotoConfiguration default].enableInvalidClickStatus = true;
    [ZLPhotoConfiguration default].enableBottomToolViewCropView = true;
    [ZLPhotoConfiguration default].languageType = ZLLanguageTypeChineseSimplified;
    [ZLPhotoConfiguration default].themeColorDeploy.bottomToolViewBgColor = RGBA(21, 24, 35, 1);
    [ZLPhotoConfiguration default].themeColorDeploy.navBarColor = RGBA(21, 24, 35, 1);
    [ZLPhotoConfiguration default].themeColorDeploy.albumListBgColor = RGBA(29, 31, 43, 1);
    [ZLPhotoConfiguration default].themeColorDeploy.thumbnailBgColor = RGBA(29, 31, 43, 1);
    [ZLPhotoConfiguration default].videoExportType = VideoExportTypeMp4;
    [ZLPhotoConfiguration default].showVideoHud = true;

    ZLPhotoPreviewSheet *sheet = [[ZLPhotoPreviewSheet alloc]initWithSelectedAssets:@[]];
    
    
    [ZLPhotoConfiguration default].previewVideoBlock = ^(NSURL * url, UIViewController * viewController) {
        dispatch_async(dispatch_get_main_queue(), ^{
            SLEditVideoController * editViewController = [[SLEditVideoController alloc] init];
            editViewController.videoPath = url;
            editViewController.isOpusList = YES;
            editViewController.modalPresentationStyle = UIModalPresentationFullScreen;
            [viewController presentViewController:editViewController animated:NO completion:nil];
        });
    };
    
    [sheet showPhotoLibraryWithSender:self];
}
#pragma mark - SocialReleaseTextHeaderViewDelegate

- (void)getOpusContentText:(NSString *)content{
    self.content = content;
}

#pragma mark - MineCreateOpusTypeHeaderViewDelegate
- (void)getcurrentOpusTagItem:(SocialSubTagModel *)itemModel{
    self.currentTagItem = itemModel;
    
    [self changeConfirmBtnStatus];
}

#pragma mark - 改变按钮状态
- (void)changeConfirmBtnStatus{
    if (self.postItems.count != 0 && self.currentTagItem.isSelect) {
        self.confirmBtn.userInteractionEnabled = YES;
        self.confirmBtn.selected = YES;
    }else{
        self.confirmBtn.userInteractionEnabled = NO;
        self.confirmBtn.selected = NO;
    }
}

#pragma mark - dealloc
- (void)dealloc{
    
}

#pragma mark - LFAssetExportSessionDelegate
- (void)assetExportSessionDidProgress:(LFAssetExportSession *)assetExportSession
{
    NSLog(@"%f", assetExportSession.progress);
}

#pragma mark - 计算文字高度
- (CGFloat)getTypeListHeight{
    CGFloat maxWidth = kScreenW - 16;
    __block CGFloat maxHeight = 32 + 20;
    __block CGFloat totalWidth = 0;
    [self.dataArray enumerateObjectsUsingBlock:^(SocialSubTagModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if (totalWidth == 0) {
            maxHeight += 32;
        };
        CGSize size = [RPAppManager getTextSizeWithText:obj.tagName font:font(12) maxSize:CGSizeMake(kScreenW, MAXFLOAT)];
        CGFloat itemWidth = ceil(size.width) + 20 + 16;
        totalWidth += itemWidth + 16;
        if (totalWidth > maxWidth) {
            maxHeight = maxHeight + 26 + 8;
            totalWidth = itemWidth + 16;
        }
    }];
    return maxHeight;
    
}

@end
